import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class ServerListeningThread implements Runnable {

	ObjectInputStream in;
	ObjectOutputStream out;
	Socket socket;
	ServerSocket serverSocket;
	public static boolean update;
	
	private Board board;
	
	ServerListeningThread(Socket socket, ServerSocket serverSocket, Board board)
	{
		//this.in = input;
		in = null;
		out = null;
		this.socket = socket;
		this.serverSocket = serverSocket;
		this.board = board;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true)
		{
			try
			{
				 if(in==null)
				 {
					 in=new ObjectInputStream(socket.getInputStream());
				 }
				 Message message= (Message) in.readObject();
				 System.out.println("Client : " + message.getMessage());	
				 
				 if(message.getMessage() == 1)
				 {
					 Server.dirChangeSinceLastUpdate -= 2;
					 System.out.println("turn left. " + "current angle at " + Server.dirChangeSinceLastUpdate);
				 }
				 else if(message.getMessage() == 2)
				 {
					 Server.dirChangeSinceLastUpdate += 2; 
					 System.out.println("turn right. " + "current angle at " + Server.dirChangeSinceLastUpdate);
				 }
				 
				 if(update == true)
				{
					 if(out==null)
					 {
						 out = new ObjectOutputStream(socket.getOutputStream());
					 }
					 
					 out.writeObject(board.getQuadTree());
					 out.flush();
					 update = false;
				 }
				 
			}
			catch(Exception e)
			{
				try {
					serverSocket.close();
					socket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
		}
	}

}
